package com.example.newsapp.activity;

import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.newsapp.R;
import com.example.newsapp.model.request.LoginRequest;
import com.example.newsapp.model.Result;
import com.example.newsapp.model.resultData.UserLoginResultData;
import com.example.newsapp.utils.HttpUtil;
import com.example.newsapp.utils.UserSessionUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    private EditText etUsername, etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private ImageView btnBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initViews();
        setupListeners();
    }

    private void initViews() {
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegister = findViewById(R.id.tvRegister);
        btnBack = findViewById(R.id.btnBack);
    }

    private void setupListeners() {
        btnBack.setOnClickListener(v -> finish());
        btnLogin.setOnClickListener(v -> attemptLogin());
        tvRegister.setOnClickListener(v -> startActivity(new Intent(this, RegisterActivity.class)));
    }

    private void attemptLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        btnLogin.setEnabled(false);
        performLogin(username, password);
    }

    private void performLogin(String username, String password) {
        LoginRequest loginRequest = new LoginRequest(username, password);
        String requestUrl = BASE_URL + "/users/login";

        Type resultType = new TypeToken<Result<UserLoginResultData>>() {
        }.getType();
        HttpUtil.request(LoginActivity.this,requestUrl, "POST", loginRequest, resultType, new HttpUtil.Callback<Result<UserLoginResultData>>() {
            @Override
            public void onSuccess(Result<UserLoginResultData> result) {
                handleLoginResult(result, username);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("网络异常" + e.getMessage());
                btnLogin.setEnabled(true);
            }
        });
    }

    private void handleLoginResult(Result<UserLoginResultData> response, String username) {

        if (response == null) {
            showToast("服务器响应异常");
            btnLogin.setEnabled(true);
            return;
        }

        if (response.getCode() == 1 && response.getData() != null) {
            UserLoginResultData data = response.getData();
            // 保存登录信息
            UserSessionUtil.saveLoginInfo(this, data.getId(), username, data.getToken());

            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();

            // 跳转到主页面
            Intent intent = new Intent(this, MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        } else {
            String errorMsg = response.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) {
                errorMsg = "未知错误";
            }
            showToast("登录失败：" + errorMsg);
        }
        btnLogin.setEnabled(true);
    }

    private void showToast(String msg) {
        Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}